<template>
  <div>
    <div v-if="choiceVisible">
      <div class="content-area" :style="ui_style">
        <div class="button-panel" v-if="isUpdate">
          <el-button
            @click="onClose"
            plain
            icon="el-icon-delete"
            size="mini"
          >返回
          </el-button>
          <el-button
            type="success"
            plain
            icon="el-icon-check"
            size="mini"
            @click="onSave"
          >保存
          </el-button>
        </div>
        <el-form ref="form" :model="form" :rules="rules"  label-width="80px" size="large">
          <el-form-item label="考试名称" prop="examName">
            <el-input v-model="form.examName" placeholder="请输入考试名称"/>
          </el-form-item>
          <el-form-item label="考试说明" prop="examDescribe">
            <el-input v-model="form.examDescribe" placeholder="请输入考试说明"/>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="8" :xs="24">
              <el-form-item label="考试/训练">
                <el-radio-group v-model="form.status">
                  <el-radio
                    v-for="dict in examStatusOptions"
                    :key="dict.value"
                    :label="dict.value"
                  >{{ dict.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>

            </el-col>
            <el-col :span="8" :xs="24" v-if="form.status==0">
              <el-form-item label="考试方式" prop="buildType">
                <el-select v-model="form.buildType" placeholder="请选择考试方式">
                  <el-option
                    v-for="dict in buildTypeOptions"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24">
              <el-form-item label="组卷方式" prop="forceDone">
                <el-radio-group v-model="form.forceDone">
                  <el-radio
                    v-for="dict in forceDoneOptions"
                    :key="dict.dictValue"
                    :label="parseInt(dict.dictValue)"
                  >{{ dict.dictLabel }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="form.forceDone===1">
            <el-col :span="8" :xs="24">
              <!-- 单选题数量 -->
              <el-form-item label="单选题数量" prop="singleChoiceCount" label-width="100px">
                <el-input-number v-model="form.singleCount" :min="0" placeholder="请输入单选题数量"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24">
              <!-- 多选题数量 -->
              <el-form-item label="多选题数量" prop="multipleChoiceCount" label-width="100px">
                <el-input-number v-model="form.multiCount" :min="0" placeholder="请输入多选题数量"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24">
              <!-- 判断题数量 -->
              <el-form-item label="判断题数量" prop="trueFalseCount" label-width="100px">
                <el-input-number v-model="form.tfCount" :min="0" placeholder="请输入判断题数量"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" >
            <el-col :span="8" :xs="24">
              <!-- 单选题数量 -->
              <el-form-item label="单选题分数" prop="singleScore" label-width="100px">
                <el-input-number v-model="form.singleScore" :min="0" placeholder="请输入单选题分数"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24">
              <!-- 多选题数量 -->
              <el-form-item label="多选题分数" prop="multiScore" label-width="100px">
                <el-input-number v-model="form.multiScore" :min="0" placeholder="请输入多选题分数"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8" :xs="24">
              <!-- 判断题数量 -->
              <el-form-item label="判断题分数" prop="tfScore" label-width="100px">
                <el-input-number v-model="form.tfScore" :min="0" placeholder="请输入判断题分数"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>


          <el-form-item label="选择题库" prop="examBank">
            <el-row>
              <el-col :span="20">
                <el-input type="textarea" :rows="2" readonly v-model="form.examBankText"/>
              </el-col>
              <el-col :span="4">
                <div class="choice-button">
                  <el-button type="primary" icon="el-icon-folder-checked" size="mini" @click="doChoice()">选择
                  </el-button>
                </div>
              </el-col>
            </el-row>

          </el-form-item>
          <el-form-item label-width="选择各题库体型占比" prop="bankProp" v-if="form.forceDone === 1">
            <el-row>
              <el-col v-for="(item, index) in form.bankProp" :key="index" :span="24">
                <h3>{{ item.bankName }}</h3>
                <el-row>
                  <el-col :span="8">
                    <el-form-item label="单选题占比" :prop="`bankProp.${index}.single`" label-width="100px">
                      <el-input-number
                        v-model="item.single"
                        :min="0"
                        :max="100"

                        label="Single Choice Ratio"
                      ></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="多选题占比" :prop="`bankProp.${index}.multi`" label-width="100px">
                      <el-input-number
                        v-model="item.multi"
                        :min="0"
                        :max="100"

                        label="Multiple Choice Ratio"
                      ></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="判断题占比" :prop="`bankProp.${index}.tf`" label-width="100px">
                      <el-input-number
                        v-model="item.tf"
                        :min="0"
                        :max="100"
                        label="Judgment Ratio"
                      ></el-input-number>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label-width="分数区间" prop="range">
            <div>
              <div v-for="(range, index) in ranges" :key="index" style="margin-bottom: 20px;">
                <el-slider
                  v-model="range.value"
                  :min="0"
                  :max="100"
                  :step="1"
                  range
                  @change="validateRanges"
                ></el-slider>
                <div>
                  <el-input
                    v-model="range.label"
                    placeholder="区间名称"
                    style="width: 200px; display: inline-block; margin-right: 10px;"
                  />
                  <span>成绩区间: {{ range.value[0] }}% - {{ range.value[1] }}%</span>
                </div>
                <el-button type="danger" @click="removeRange(index)">删除</el-button>
              </div>
              <el-button @click="addRange" type="primary">添加区间</el-button>
              <!--              <div>-->
              <!--                <p v-if="total !== 100" style="color: red;">区间总和必须为 101</p>-->
              <!--                <p>区间总和: {{ total }}</p>-->
              <!--              </div>-->
            </div>
          </el-form-item>
          <el-form-item label="标题图片" prop="pictureUrl">
            <el-upload
              class="avatar-uploader"
              :action="url"
              :data="upLoadData"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="imageUrl"
                :src="imageUrl"
                class="avatar"
              >
              <i
                v-else
                class="el-icon-plus avatar-uploader-icon"
              ></i>
            </el-upload>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12" :xs="24">
              <el-form-item label="开始时间" prop="startDate" >
                <el-date-picker
                  v-model="form.startDate"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetime"
                  placeholder="选择考试开始日期时间"

                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" :xs="24">
              <el-form-item label="考试时长" prop="examDuration">
                <el-time-select
                  v-model="form.examDuration"
                  :picker-options="{
		                start: '00:15',
		                step: '00:15',
		                end: '24:00'
		              }"
                  @change="onTimeChange"
                  placeholder="选择时间"
                >
                </el-time-select>
              </el-form-item>
            </el-col>
          </el-row>
          <!--          <el-form-item label="状态">-->
          <!--            <el-radio-group v-model="form.status">-->
          <!--              <el-radio-->
          <!--                v-for="dict in statusOptions"-->
          <!--                :key="dict.dictValue"-->
          <!--                :label="parseInt(dict.dictValue)"-->
          <!--              >{{ dict.dictLabel }}-->
          <!--              </el-radio>-->
          <!--            </el-radio-group>-->
          <!--          </el-form-item>-->


        </el-form>
        <!-- 剪裁组件弹窗 -->
        <el-dialog
          title="裁切题库封面"
          :visible.sync="cropperModel"
          width="950px"
          center
        >
          <cropper-image
            :Name="cropperName"
            @uploadImgSuccess="handleUploadSuccess"
            ref="child"
          >
          </cropper-image>
        </el-dialog>
      </div>
    </div>
    <div v-else>
      <exam-select ref="selectRef" @refreshSelect="selectDoneHandle"></exam-select>
    </div>
  </div>
</template>

<script>
import { baseApiUrl } from '@/config/sysinfo'
import examSelect from '@/components/ExamSelect/index'
import CropperImage from './CropperImage'
import { listQuestionsbankBycode } from '@/api/questions/questionsbank'
import { updateExamtask } from '@/api/exam/examtask'
import { dateToString, dateTextToDateString, dateRemoveSeconds, dateTextToDatetimeString } from '@/utils/dateUtils'
import { listQuestions, listQuestionsNoPage } from '@/api/questions/questionslist'

export default {
  components: {
    examSelect,
    CropperImage
  },
  data() {
    return {

      selectedQuestions: [], // 存储选取的题目 ID
      allSingleCount: 0,
      allMultiCount: 0,
      allTfCount: 0,
      allList: [],
      // bankProp: [],
      singleCount: 1,
      tfCount: 1,
      multiCount: 1,
      choiceVisible: true,
      // 状态字典
      statusOptions: [],
      ui_style: null,
      hosturl: '',
      // 表单参数
      form: {
        singleScore: 2,
        multiScore: 2,
        tfScore: 2,
        bankProp: []
      },
      ranges: [
        { label: '不及格', value: [0, 60] },
        { label: '及格', value: [61, 80] },
        { label: '优秀', value: [81, 90] },
        { label: '特别优秀', value: [91, 100] }
      ],
      examStatusOptions: [{ label: '考试', value: 0 }, { label: '训练', value: 1 }],
      // 表单校验
      rules: {
        examCode: [
          { required: true, message: '考试代码不能为空', trigger: 'blur' }
        ],
        examName: [
          { required: true, message: '考试名称不能为空', trigger: 'blur' }
        ],
        buildType: [
          { required: true, message: '考试方式不能为空', trigger: 'change' }
        ],
        examBank: [
          { required: true, message: '题库必须选择', trigger: 'change' }
        ],
        examDuration: [
          { required: true, message: '考试时长不能为空', trigger: 'change' }
        ],
        startDate: [
          { required: true, message: '考试开始时间不能为空', trigger: 'change' }
        ],
        pictureUrl: [
          { required: true, message: '标题图片不能为空', trigger: 'change' }
        ]
      },
      buildTypeOptions: [
        { dictValue: 1, dictLabel: '固定顺序' },
        // {dictValue: 2, dictLabel: "随机抽题"},
        { dictValue: 3, dictLabel: '考时打乱顺序' }
      ],
      choiceList: null,
      forceDoneOptions: [
        { dictValue: 0, dictLabel: '人工组卷' },
        { dictValue: 1, dictLabel: '随机组卷' }
      ],
      imageUrl: null,
      startDate: new Date(),
      url: '',
      upLoadData: {
        guidCode: ''
      },
      cropperModel: false,
      cropperName: '',
      isUpdate: false
    }
  },
  created() {
    const s_width = document.body.clientWidth
    console.log('s_width')
    console.log(s_width)
    if (s_width < 1000) {
      this.ui_style = 'margin-left: 4%; margin-right: 4%;'
    } else if (s_width >= 1000 && s_width < 1366) {
      this.ui_style = 'margin-left: 4%; margin-right: 4%;'
    } else if (s_width >= 1366 && s_width < 1566) {
      this.ui_style = 'margin-left: 4%; margin-right: 4%;'
    } else if (s_width >= 1566 && s_width < 1766) {
      this.ui_style = 'margin-left: 4%; margin-right: 4%;'
    } else {
      this.ui_style = 'margin-left: 4%; margin-right: 4%;'
    }

    //
    // if (s_width < 1000) {
    //   this.ui_style = 'margin-left: 2%; margin-right: 2%; font-size: 12px;';
    // } else if (s_width >= 1000 && s_width < 1366) {
    //   this.ui_style = 'margin-left: 8%; margin-right: 8%; font-size: 14px;';
    // } else if (s_width >= 1366 && s_width < 1566) {
    //   this.ui_style = 'margin-left: 12%; margin-right: 12%; font-size: 16px;';
    // } else if (s_width >= 1566 && s_width < 1766) {
    //   this.ui_style = 'margin-left: 18%; margin-right: 18%; font-size: 18px;';
    // } else {
    //   this.ui_style = 'margin-left: 24%; margin-right: 24%; font-size: 20px;';
    // }


    this.hosturl = process.env.VUE_APP_BASE_API
    this.getDicts('sys_normal_disable').then(response => {
      this.statusOptions = response.data
    })
  },
  watch: {
    'form.status': function(newStatus) {
      if (newStatus === 1) {
        this.form.buildType = 1 // 将 buildType 设为 1
      }
    },
    choiceList: {
      handler(newValue) {
        console.log(newValue)
        let list = []
        if (newValue !== null && newValue.length > 0) {
          const totalQuestions = newValue.length // 获取题库总数
          let baseValue = Math.floor(100 / totalQuestions) // 基础分配值（向下取整）
          let remaining = 100 - baseValue * totalQuestions // 剩余的百分比
          let bankCodes = []
          for (let i = 0; i < totalQuestions; i++) {
            list.push({
              'bankCode': newValue[i].bankCode,
              'single': baseValue,
              'multi': baseValue,
              'tf': baseValue,
              'bankName': newValue[i].bankName,
              'choiceNumber': newValue[i].choiceNumber,
              'judgeNumber': newValue[i].judgeNumber,
              'radioNumber': newValue[i].radioNumber
            })
            bankCodes.push(newValue[i].bankCode)
          }

          // 处理剩余部分，将剩余的部分分配给前面的题库
          for (let i = 0; i < remaining; i++) {
            list[i].single += 1 // 将多余的1%均匀分配到题库中
            list[i].multi += 1 // 将多余的1%均匀分配到题库中
            list[i].tf += 1 // 将多余的1%均匀分配到题库中
          }

          listQuestionsNoPage({ 'bankCodes': bankCodes }).then(response => {
            this.allList = response.rows

            // 遍历 allList，根据 questionsType 计算数量
            this.allList.forEach(item => {
              if (item.questionsType === 1) {
                this.allTfCount += 1 // 判断题
              } else if (item.questionsType === 2) {
                this.allSingleCount += 1 // 单选题
              } else if (item.questionsType === 3) {
                this.allMultiCount += 1 // 多选题
              }
            })
          })
        }

        // 按照 single、multi、tf 三个题型的总和对 list 进行排序，题目多的排在后面

        list.sort((a, b) => (a.choiceNumber + a.judgeNumber + a.radioNumber) - (b.choiceNumber + b.judgeNumber + b.radioNumber))
        // 使用 Vue 的 $set 确保响应式更新

        this.$set(this.form, 'bankProp', list)
      },
      deep: true // 深度监听
    }
  },
  computed: {
    total() {
      return this.ranges.reduce((sum, range) => {
        return sum + (range.value[1] - range.value[0] + 1) // +1 来计算包含的值
      }, 0)
    }
  },

  methods: {
    validateRanges() {
      // 检查重叠
      let hasOverlap = false

      // 直接使用 computed 属性 total 的值
      const currentSum = this.total // 获取计算的总和

      // 检查重叠
      for (let i = 0; i < this.ranges.length; i++) {
        const range = this.ranges[i].value
        for (let j = 0; j < this.ranges.length; j++) {
          if (i !== j) {
            const compareRange = this.ranges[j].value
            if (this.isOverlapping(range, compareRange)) {
              hasOverlap = true
              break // 找到重叠后，退出内层循环
            }
          }
        }
      }

      // 提示用户
      if (currentSum > 101) {
        this.$message.error('区间总和不能超过100')
        return false
      } else if (currentSum < 101) {
        this.$message.error('区间总和必须等于100')
        return false
      } else if (hasOverlap) {
        this.$message.error('区间不能重叠')
        return false
      } else {
        return true
      }
    },

    isOverlapping(range1, range2) {
      return range1[0] < range2[1] && range2[0] < range1[1]
    },
    addRange() {
      this.ranges.push({ label: `新区间`, value: [0, 0] })
    },
    removeRange(index) {
      this.ranges.splice(index, 1)
    }
    ,

    init_data(contentdata, choicelist) {
      this.isUpdate = false
      if (contentdata.examCode !== undefined && contentdata.examCode !== null) {
        this.form = contentdata
        if (this.form.pictureUrl !== undefined && this.form.pictureUrl !== null) {
          this.imageUrl = this.hosturl + this.form.pictureUrl
        }
      }

      if (choicelist !== undefined && choicelist !== null) {
        this.choiceList = choicelist
      }
    },
    update_data(row) {
      this.isUpdate = true
      row.forceDone = Number(row.forceDone)
      row.buildType = Number(row.buildType)

      this.form = row
      if (this.form.pictureUrl !== undefined && this.form.pictureUrl !== null) {
        this.imageUrl = this.hosturl + this.form.pictureUrl
      }
      this.startDate = row.startTime
      listQuestionsbankBycode(row.examBank).then(response => {
        this.choiceList = response.data
      })
    },
    doChoice() {
      this.choiceVisible = false
      this.$store.commit('SET_SHOWTITLE', false)
      this.$nextTick(() => {
        this.$refs.selectRef.init_data(this.choiceList)
      })
    },
    selectDoneHandle(saveList) {
      this.$store.commit('SET_SHOWTITLE', true)
      this.choiceList = saveList
      this.choiceVisible = true

      let nametext = ''
      let codetext = ''
      if (this.choiceList !== null && this.choiceList.length > 0) {
        for (let i = 0; i < this.choiceList.length; i++) {

          if (i < this.choiceList.length - 1) {
            nametext += this.choiceList[i].bankName + ','
            codetext += this.choiceList[i].bankCode + ','
          } else {
            nametext += this.choiceList[i].bankName
            codetext += this.choiceList[i].bankCode
          }
        }
      }
      this.form.examBankText = nametext
      this.form.examBank = codetext
    },

    onTimeChange() {
      if (this.startDate === undefined || this.startDate === null) {
        this.form.examDuration = undefined
        this.$message.error('请先输入考试开始时间')
        return
      }
      this.set_time()
    },
    set_time() {
      let timeitem = this.form.examDuration.split(':')
      const addhour = Number(timeitem[0]) * 60 * 60 * 1000
      const addminute = Number(timeitem[1]) * 60 * 1000
      const datestr = dateRemoveSeconds(new Date(this.startDate))
      this.form.startTime = Number(new Date(datestr).getTime())
      this.form.endTime = this.form.startTime + addhour + addminute
    },
    getData() {
      if (this.onCheck()) {
        const saveData = {
          choiceList: this.choiceList,
          examData: this.form
        }
        return saveData
      } else {
        return null
      }
    },
    saveData() {
      if (this.onCheck()) {
        this.set_time()
        updateExamtask(this.form).then(response => {
          this.msgSuccess('修改成功')
          return true
        })
      } else {
        return false
      }
    },
    onClose() {
      this.$emit('refreshContent')
    },
    onSaveOrBack() {
      if (this.saveData()) {
        this.$emit('refreshContent')
      }
    },
    onSave() {
      this.saveData()
    },
    calculateTotalScore() {
      let score = this.form.singleCount * this.form.singleScore + this.form.multiCount * this.form.multiScore + this.form.tfCount * this.form.tfScore
      console.log('score')
      console.log(score)
      return (score === 100) // 判断是否等于100
    },
    onCheck() {

      this.validateRanges()
      if (this.form.status==0){
        let s = this.calculateTotalScore()
        if (!s) {
          this.$message.error('总分必须等于100分')
          return false
        }
      }


      if (this.form.forceDone == 1 && this.form.singleCount > this.allSingleCount) {
        this.$message.error('当前题库共' + this.allSingleCount + '道单选题,您选择了' + this.form.singleCount + '道,请重新选择。')
        return false // 阻止提交
      }
      if (this.form.forceDone == 1 && this.form.multiCount > this.allMultiCount) {
        this.$message.error('当前题库共' + this.allMultiCount + '道多选题,您选择了' + this.form.multiCount + '道,请重新选择。')
        return false // 阻止提交
      }
      if (this.form.forceDone == 1 && this.form.tfCount > this.allTfCount) {
        this.$message.error('当前题库共' + this.allTfCount + '道判断题,您选择了' + this.form.tfCount + '道,请重新选择。')
        return false // 阻止提交
      }

      if (this.form.examName === undefined || this.form.examName === null) {
        this.$message.error('需要输入考试名称')
        return false
      }

      if (this.form.buildType === undefined || this.form.buildType === null) {
        this.$message.error('需要先选择考试方式')
        return false
      }

      if (this.form.examBankText === undefined || this.form.examBankText === null) {
        this.$message.error('需要先选择题库')
        return false
      }

      if (this.form.pictureUrl === undefined || this.form.pictureUrl === null) {
        this.$message.error('需要先加入标题图片')
        return false
      }

      if (this.startDate === undefined || this.startDate === null) {
        this.$message.error('需要输入考试开始时间')
        return false
      }

      if (this.form.examDuration === undefined || this.form.examDuration === null) {
        this.$message.error('需要输入考试时长')
        return false
      }
      let totalSingle = 0
      if (this.form.bankProp != null && this.form.bankProp.length > 0) {
        totalSingle = this.form.bankProp.reduce((sum, item) => sum + item.single, 0)
      }
      if (totalSingle !== 100) {
        this.$message.error('单选题占比总和必须等于 100%')
        return false // 阻止提交
      }
      const totalMulti = this.form.bankProp.reduce((sum, item) => sum + item.multi, 0)

      if (totalMulti !== 100) {
        this.$message.error('多选题占比总和必须等于 100%')
        return false // 阻止提交
      }
      const totalTf = this.form.bankProp.reduce((sum, item) => sum + item.tf, 0)

      if (totalTf !== 100) {
        this.$message.error('判断题占比总和必须等于 100%')
        return false // 阻止提交
      }
      if (this.form.startTime === undefined || this.form.startTime === null) {
        this.set_time()
      }

      if (this.form.forceDone == 1) {

        let errorMessage = ''
        let totalRequiredSingle = 0
        let totalRequiredMulti = 0
        let totalRequiredTf = 0

// 使用 Math.round() 进行四舍五入计算题目需求量
        this.form.bankProp.forEach(bank => {
          totalRequiredSingle += Math.floor(bank.single * this.form.singleCount / 100)
          totalRequiredMulti += Math.floor(bank.multi * this.form.multiCount / 100)
          totalRequiredTf += Math.floor(bank.tf * this.form.tfCount / 100)
        })

// 确保总需求量等于用户设置的数量
        totalRequiredSingle = Math.min(totalRequiredSingle, this.form.singleCount)
        totalRequiredMulti = Math.min(totalRequiredMulti, this.form.multiCount)
        totalRequiredTf = Math.min(totalRequiredTf, this.form.tfCount)

// 清空已选择的题目数组
        this.selectedQuestions = []

// 存储每个题库的实际选择情况
        let actualSelections = this.form.bankProp.map(bank => ({
          bankName: bank.bankName,
          selectedSingle: [],
          selectedMulti: [],
          selectedTf: []
        }))

        let totalActualSingle = 0
        let totalActualMulti = 0
        let totalActualTf = 0

        this.form.bankProp.forEach((bank, index) => {
          let bankCode = bank.bankCode

          // 找到对应题库中的题目
          let correspondingQuestions = this.allList.filter(item => item.bankCode === bankCode)

          // 计算不同题型的题目数量
          let totalSingleQuestions = correspondingQuestions.filter(q => q.questionsType === 2)
          let totalMultiQuestions = correspondingQuestions.filter(q => q.questionsType === 3)
          let totalTfQuestions = correspondingQuestions.filter(q => q.questionsType === 1)

          // 使用 Math.round() 四舍五入计算每个题库的需求量
          let requiredSingleQuestions = Math.floor(bank.single * this.form.singleCount / 100)
          let requiredMultiQuestions = Math.floor(bank.multi * this.form.multiCount / 100)
          let requiredTfQuestions = Math.floor(bank.tf * this.form.tfCount / 100)

          // 错误处理 - 如果题目不足
          if (requiredSingleQuestions > totalSingleQuestions.length) {
            errorMessage += `题库 ${bank.bankName} 中的单选题数量不足，需 ${requiredSingleQuestions} 道题，实际只有 ${totalSingleQuestions.length} 道题。\n`
          }

          if (requiredMultiQuestions > totalMultiQuestions.length) {
            errorMessage += `题库 ${bank.bankName} 中的多选题数量不足，需 ${requiredMultiQuestions} 道题，实际只有 ${totalMultiQuestions.length} 道题。\n`
          }

          if (requiredTfQuestions > totalTfQuestions.length) {
            errorMessage += `题库 ${bank.bankName} 中的判断题数量不足，需 ${requiredTfQuestions} 道题，实际只有 ${totalTfQuestions.length} 道题。\n`
          }

          // 随机选择题目
          let selectedSingle = this.getRandomQuestions(totalSingleQuestions, requiredSingleQuestions)
          let selectedMulti = this.getRandomQuestions(totalMultiQuestions, requiredMultiQuestions)
          let selectedTF = this.getRandomQuestions(totalTfQuestions, requiredTfQuestions)

          // 记录选择的题目
          actualSelections[index].selectedSingle = selectedSingle
          actualSelections[index].selectedMulti = selectedMulti
          actualSelections[index].selectedTf = selectedTF

          // 计算已选择的题目数量
          totalActualSingle += selectedSingle.length
          totalActualMulti += selectedMulti.length
          totalActualTf += selectedTF.length

          // 添加到已选题目中
          this.selectedQuestions.push(...selectedSingle, ...selectedMulti, ...selectedTF)
        })

// 补齐最后一个题库的差额
        let lastBankIndex = this.form.bankProp.length - 1
        let singleDifference = this.form.singleCount - totalActualSingle
        let multiDifference = this.form.multiCount - totalActualMulti
        let tfDifference = this.form.tfCount - totalActualTf

        if (singleDifference > 0 || multiDifference > 0 || tfDifference > 0) {
          console.log('补齐差额')

          let correspondingQuestions = this.allList.filter(item => item.bankCode === this.form.bankProp[lastBankIndex].bankCode)

          let totalSingleQuestions = correspondingQuestions.filter(q => q.questionsType === 2)
          let totalMultiQuestions = correspondingQuestions.filter(q => q.questionsType === 3)
          let totalTfQuestions = correspondingQuestions.filter(q => q.questionsType === 1)

          // 补充剩余的单选题
          if (singleDifference > 0) {
            let additionalSingle = this.getRandomQuestions(totalSingleQuestions, singleDifference)
            actualSelections[lastBankIndex].selectedSingle.push(...additionalSingle)
            if (additionalSingle.length < singleDifference) {
              this.$message.error(`题库 ${this.form.bankProp[lastBankIndex].bankName}中单选题题可分配题目不足，请重新选择`)
              return false
            }
          }
          // 补充剩余的多选题
          if (multiDifference > 0) {
            let additionalMulti = this.getRandomQuestions(totalMultiQuestions, multiDifference)
            console.log('补充剩余的多选题')
            console.log(additionalMulti)
            if (additionalMulti.length < multiDifference) {
              this.$message.error(`题库 ${this.form.bankProp[lastBankIndex].bankName}中多选题可分配题目不足，请重新选择`)
              return false
            }
            actualSelections[lastBankIndex].selectedMulti.push(...additionalMulti)
          }

          // 补充剩余的判断题
          if (tfDifference > 0) {
            let additionalTf = this.getRandomQuestions(totalTfQuestions, tfDifference)
            actualSelections[lastBankIndex].selectedTf.push(...additionalTf)
            if (additionalTf.length < tfDifference) {
              this.$message.error(`题库 ${this.form.bankProp[lastBankIndex].bankName}中判断题可分配题目不足，请重新选择`)
              return false
            }
          }

          // 更新最终选择的题目
          this.selectedQuestions = []

          actualSelections.forEach(selection => {
            this.selectedQuestions.push(...selection.selectedSingle, ...selection.selectedMulti, ...selection.selectedTf)
          })
        }

// 分配选中的题目ID到表单
        this.form.selectedQuestions = this.selectedQuestions

        // 如果有错误信息，弹出提示
        if (errorMessage) {
          this.$message.error(errorMessage)
          return false
        }

      }
      this.form.ranges = this.ranges
      return true
    },

    getRandomQuestions(questions, count) {
      const shuffled = questions.sort(() => 0.5 - Math.random()) // 随机打乱题目顺序
      return shuffled.slice(0, count).map(q => q.questionsCode) // 选取前 count 个题目 ID
    },

    beforeAvatarUpload(file) {
      this.cropperModel = true
      this.cropperName = name
      this.$nextTick(() => {
        this.$refs.child.selectImg(this.form.examCode, file)
      })
    },
    // 图片上传成功后
    handleUploadSuccess(data) {
      this.imageUrl = this.hosturl + data.photoUrl
      this.form.pictureUrl = data.photoUrl
      this.cropperModel = false
    }
  }
}
</script>

<style scoped lang="scss">
.content-area {
  margin-top: 1.6rem;
  background-color: #f7f7f7;
}

.button-panel {
  padding-bottom: 1.6rem;
  background-color: #fff;
}

.form-area {
  padding-top: 1.6rem;
  background-color: #fff;
}

.choice-button {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
  background-color: #fff;
}

.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>


